package com.atguigu.crowd.filetr;

import com.atguigu.crowd.constant.AccessPassResources;
import com.atguigu.crowd.constant.CrowdContant;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class CrowdAccessFilter extends ZuulFilter {
    /**
     *
     * @return
     */
    @Override
    public String filterType() {
        // 这里返回“pre”意思是在目标微服务前执行过滤
        return "pre";
    }

    /**
     * filter的执行优先级
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 判断是否需要过滤的方法
     * @return
     */
    @Override
    public boolean shouldFilter() {

        //获取RequestContext对象
        RequestContext requestContext = RequestContext.getCurrentContext();

        // 2.通过 RequestContext 对象获取当前请求对象
        // （框架底层是借助 ThreadLocal 从当前 线程上获取事先绑定的 Request 对象）
        HttpServletRequest request = requestContext.getRequest();

        String servletPath = request.getServletPath();

        boolean passResult = AccessPassResources.PASS_RES_SET.contains(servletPath);

        //发挥false表示不执行过滤方法
        //放行指定的请求路径
        if (passResult){
            return false;
        }

        boolean staticResult = AccessPassResources.judgeCurrentServletPathWetherStaticResource(servletPath);

        //放行静态资源
        if (staticResult){
            return false;
        }


        return true;
    }

    /**
     * 执行过滤的方法
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {

        RequestContext requestContext = RequestContext.getCurrentContext();

        HttpServletRequest request = requestContext.getRequest();

        HttpSession session = request.getSession();

        Object member = session.getAttribute(CrowdContant.ATTR_NAME_MEMBER);

        //没有登录
        if (member==null){

            session.setAttribute(CrowdContant.ATTR_MAME_MESSAGE,CrowdContant.MESSAGE_ACCESS_FORBIDEN);

            HttpServletResponse response = requestContext.getResponse();

            try {
                //重定向到登录页面
                response.sendRedirect("/auth/to/member/login/page");

            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return null;
    }
}
